from docx import Document

class DocumentParser:
    def __init__(self):
        self.questions = []
        self.answers = []
        self.explanations = []
    
    def parse_document(self, file_path):
        doc = Document(file_path)
        current_question = []
        current_answer = ""
        current_explanation = ""
        in_table_data = False
        table_content = []
        
        # 中文数字映射
        chinese_nums = {
            "１": "1", "２": "2", "３": "3", "４": "4", "５": "5",
            "６": "6", "７": "7", "８": "8", "９": "9", "０": "0"
        }
        
        for paragraph in doc.paragraphs:
            text = paragraph.text.strip()
            if not text:  # 跳过空行
                continue
            
            # 处理中文数字
            for cn, en in chinese_nums.items():
                text = text.replace(cn, en)
            
            # 检查是否是表格数据的开始
            if "数据库结构" in text or "表结构" in text:
                in_table_data = True
                table_content = [text]
                continue
            
            # 如果在处理表格数据
            if in_table_data:
                # 检查是否已经到达表格结束
                if text.startswith(("A．", "A.", "A、", "A ", "A)")):
                    in_table_data = False
                    current_question.extend(table_content)
                else:
                    table_content.append(text)
                    continue
            
            # 检查是否是新题目（支持多种格式）
            if (any(text.startswith(f"{i}．") or  # 全角点
                   text.startswith(f"{i}.") or   # 半角点
                   text.startswith(f"{i}、") or  # 顿号
                   text.startswith(f"{i} ") or   # 空格
                   text.startswith(f"{i}：") or  # 全角冒号
                   text.startswith(f"{i}:") or   # 半角冒号
                   text.startswith(f"{i}．")     # 另一种全角点
                   for i in range(1, 1000)) or 
                text.startswith("题目")):
                
                # 保存上一题的内容
                if current_question:
                    self.questions.append("\n".join(current_question))
                    self.answers.append(current_answer)
                    self.explanations.append(current_explanation)
                
                # 处理括号中的答案
                # 先检查中文括号
                if "（" in text and "）" in text:
                    answer_start = text.find("（")
                    answer_end = text.find("）")
                    if answer_end > answer_start:
                        answer = text[answer_start+1:answer_end].strip()
                        if answer in ["A", "B", "C", "D"]:
                            current_answer = f"答案：{answer}"
                            text = text[:answer_start] + "（）" + text[answer_end+1:]
                # 再检查英文括号
                if "(" in text and ")" in text:
                    answer_start = text.find("(")
                    answer_end = text.find(")")
                    if answer_end > answer_start:
                        answer = text[answer_start+1:answer_end].strip()
                        if answer in ["A", "B", "C", "D"]:
                            current_answer = f"答案：{answer}"
                            text = text[:answer_start] + "()" + text[answer_end+1:]
                # 处理混合括号（中文括号包含英文括号的情况）
                if "（" in text and ")" in text:
                    answer_start = text.find("（")
                    answer_end = text.find(")")
                    if answer_end > answer_start:
                        answer = text[answer_start+1:answer_end].strip()
                        if answer in ["A", "B", "C", "D"]:
                            current_answer = f"答案：{answer}"
                            text = text[:answer_start] + "（）" + text[answer_end+1:]
                # 处理混合括号（英文括号包含中文括号的情况）
                if "(" in text and "）" in text:
                    answer_start = text.find("(")
                    answer_end = text.find("）")
                    if answer_end > answer_start:
                        answer = text[answer_start+1:answer_end].strip()
                        if answer in ["A", "B", "C", "D"]:
                            current_answer = f"答案：{answer}"
                            text = text[:answer_start] + "()" + text[answer_end+1:]
                
                # 开始新的题目
                current_question = [text]
                current_explanation = ""
                in_table_data = False
                table_content = []
            
            # 检查选项（支持更多格式）
            elif (text.startswith(("A)", "B)", "C)", "D)")) or
                  text.startswith(("A.", "B.", "C.", "D.")) or
                  text.startswith(("A、", "B、", "C、", "D、")) or
                  text.startswith(("A ", "B ", "C ", "D ")) or
                  text.startswith(("A．", "B．", "C．", "D．"))):
                current_question.append(text)
            
            # 检查答案（支持多种格式）
            elif text.startswith("答案") or text.startswith("正确答案"):
                # 提取答案字母
                if "：" in text:
                    answer_text = text.split("：")[-1].strip()
                elif ":" in text:
                    answer_text = text.split(":")[-1].strip()
                else:
                    answer_text = text.replace("答案", "").replace("正确答案", "").strip()
                
                # 去掉可能的标点
                answer_text = answer_text.rstrip("。.。，,；;")
                current_answer = f"答案：{answer_text}"
            
            # 检查题目说明（不使用"解析"关键词）
            elif "解析】" in text:
                # 直接跳过包含"解析】"的行
                continue
            elif text.startswith("【") or text.startswith("[") or text.startswith("说明：") or text.startswith("说明:"):
                # 去掉各种标记
                current_explanation = text
                if text.startswith("【") and "】" in text:
                    current_explanation = text[text.index("】")+1:].strip()
                elif text.startswith("[") and "]" in text:
                    current_explanation = text[text.index("]")+1:].strip()
                elif text.startswith("说明"):
                    current_explanation = text.replace("说明：", "").replace("说明:", "").strip()
            elif current_explanation and not (text.startswith("答案") or text.startswith("正确答案")):
                # 继续添加说明内容
                current_explanation += "\n" + text
            
            # 如果不是特殊行，就添加到当前题目中
            else:
                current_question.append(text)
        
        # 添加最后一组题目
        if current_question:
            self.questions.append("\n".join(current_question))
            self.answers.append(current_answer)
            self.explanations.append(current_explanation)
        
        return self.questions, self.answers, self.explanations 